package net.hserver.sync.driver;

import cn.hutool.core.io.FileUtil;
import com.github.sardine.DavResource;
import com.github.sardine.Sardine;
import com.github.sardine.impl.SardineImpl;
import lombok.Data;
import lombok.SneakyThrows;
import net.hserver.sync.file.FileMonitor;
import net.hserver.sync.util.PathUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import static net.hserver.sync.util.PathUtil.pathJoinUrl;

@Data
public class WebDavDriver implements Driver {
    private static final Logger log = LoggerFactory.getLogger(WebDavDriver.class);
    private final String host;
    private final Sardine sardine;
    private final String rootPath;

    private final FileMonitor fileMonitor;

    public WebDavDriver(String host, String username, String password, String rootPath, FileMonitor fileMonitor) {
        int i = host.indexOf("/", 9);
        if (i > 0) {
            this.host = host.substring(0, i);
            this.rootPath = host.substring(i) + rootPath;
        } else {
            this.host = host;
            this.rootPath = rootPath;
        }
        this.sardine = new SardineImpl(username, password);
        this.fileMonitor = fileMonitor;
    }

    public FileMonitor getFileMonitor() {
        return fileMonitor;
    }

    @Override
    public List<DavResource> list(String path, int depth) {
        try {
            return sardine.list(pathJoinUrl(host, path), depth);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @SneakyThrows
    @Override
    public void mkdirAll(String path) {
        String s = pathJoinUrl(host, path);
        sardine.createDirectory(s);
    }

    @Override
    public void delete(String path) {
        try {
            sardine.delete(pathJoinUrl(host, path));
        }catch (Exception e){}
    }

    @SneakyThrows
    @Override
    public void put(String path,  String filePath) {
        String s = pathJoinUrl(host, path);
        String s1 = PathUtil.pathUrlParent(s);
        if (!sardine.exists(s1)){
            log.debug("创建目录：{}",s1);
            sardine.createDirectory(s1);
        }
        log.debug("上传文件到：{}",s);
        sardine.put(s, new File(filePath),null);
    }

    @SneakyThrows
    @Override
    public boolean exists(String path) {
        return sardine.exists(pathJoinUrl(host, path));
    }


    @SneakyThrows
    @Override
    public InputStream get(String path) {
        return sardine.get(pathJoinUrl(host, path));
    }

}
